// 
//  Author:
//    Andy Selvig ajselvig@gmail.com
// 
//  Copyright (c) 2010, Andy Selvig
// 
//  All rights reserved.
// 
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 
//     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
//       the documentation and/or other materials provided with the distribution.
//     * Neither the name of the [ORGANIZATION] nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// 
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
//  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// 
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using CommandLine;

namespace Shake
{
	/// <summary>
	/// Entry point for the Shake command line application.
	/// </summary>
	class Program
	{

		public static void Main(string[] args)
		{
			new Program(args);
		}


		public Program(string[] args)
		{
			_searchPaths = new List<string>() { ".", "lib"};

			try
			{
                _options = new Options();
				ICommandLineParser parser = new CommandLineParser();
                if (args.Length > 0 && parser.ParseArguments(args, _options))
                {
                    // create the task manager
                    _manager = new TaskManager();
                    _manager.Output = Console.Out;
                    if (_options.Verbose)
                        _manager.Verbose = _options.Verbose;

                    // look for assemblies
                    LookForAssemblies();

                    // print tasks
                    if (_options.ListTasks)
                    {
                        ListTasks();
                        return;
                    }

                    // execute the tasks
                    ExecuteTasks();
                }
                else // didn't parse options
                {
                    Console.WriteLine(_options.GetUsage());
                }

			}
			catch (Exception ex)
			{
				Console.WriteLine("ERROR: {0}\n{1}", ex.Message, _options.Verbose ? ex.StackTrace : "");
			}
		}

		/// <summary>
		/// Paths in which to look for assemblies.
		/// </summary>
		private List<string> _searchPaths;

		private TaskManager _manager;

        private Options _options;

        /// <summary>
        /// Looks for assemblies in the search path.
        /// </summary>
        private void LookForAssemblies()
        {
            foreach (var path in _searchPaths)
            {
                var fullPath = Path.Combine(Directory.GetCurrentDirectory(), path);
                if (Directory.Exists(fullPath))
                {
                    ProcessDirectory(fullPath);
                }
                else if (File.Exists(fullPath))
                {

                }
            }
        }
        
		/// <summary>
		/// Processes the directory to look for Shakefiles or assemblies. 
		/// </summary>
		private void ProcessDirectory(string dir)
		{
            if (_manager.Verbose)
			    Console.WriteLine("-- Processing {0}", dir);
			var files = Directory.GetFiles(dir);
			foreach (var file in files)
			{
				if (file.ToLower().EndsWith("shakefile"))
				{
					var reader = new StreamReader(file);
					var line = reader.ReadLine();
					while (line != null)
					{
						var path = Path.Combine(dir, line);
						if (Directory.Exists(path))
							ProcessDirectory(path);
						if (File.Exists(path) && file.ToLower().EndsWith("shakefile"))
							LoadAssembly(path);
						line = reader.ReadLine();
					}
					reader.Close();
				}
			}
		}

		/// <summary>
		/// Loads an assembly from the given file.
		/// </summary>
		private void LoadAssembly(string path)
        {
            if (_manager.Verbose)
			    Console.WriteLine("-- Loading assembly {0}", path);
			var asm = Assembly.LoadFrom(path);
			_manager.LoadAssembly(asm);
		}

        /// <summary>
        /// Lists all tasks in the manager.
        /// </summary>
        private void ListTasks()
        {
            foreach (var group in _manager.TaskGroups)
            {
                foreach (var task in group.Tasks)
                {
                    Console.WriteLine("  {0}:{1} - {2}", group.Namespace, task.Name, task.Description);
                }
            }
        }

        /// <summary>
        /// Executes all tasks specified by the options.
        /// </summary>
        private void ExecuteTasks()
        {
            // collect the tasks before executing them
            var tasks = new List<TaskAttribute>();
            foreach (var taskName in _options.Tasks)
            {
                var task = _manager.FindTask(taskName);
                if (task == null)
                {
                    throw new Exception(String.Format("Could not find task named {0}", taskName));
                }
                tasks.Add(task);
            }

            // we found all the tasks, so execute them in order
            foreach (var task in tasks)
            {
                task.Execute();
            }
        }
		
	}
}

